package com.quickboot.core.handle;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import cn.hutool.core.util.StrUtil;
import com.quickboot.common.entity.Result;
import com.quickboot.common.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.RedisConnectionFailureException;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理
 *
 * @author Tellsea
 * @date 2022/11/21
 */
@Slf4j
@RestControllerAdvice
@Order(value = Ordered.HIGHEST_PRECEDENCE)
public class GlobalExceptionHandle {

    @ExceptionHandler(value = BusinessException.class)
    public Result handleBusinessException(BusinessException e) {
        log.error("【错误异常】{}", e.getClass());
        log.error("【错误描述】{}", e.getMessage());
        return Result.fail(e.getMessage());
    }

    @ExceptionHandler(value = NotLoginException.class)
    public Result handleNotLoginException(NotLoginException e) {
        log.error("【错误异常】{}", e.getClass());
        log.error("【错误描述】{}", e.getMessage());
        return Result.fail(401, "登录失效，请重新登录");
    }

    @ExceptionHandler(value = NotPermissionException.class)
    public Result handleNotPermissionException(NotPermissionException e) {
        log.error("【错误异常】{}", e.getClass());
        log.error("【错误描述】{}", e.getMessage());
        return Result.fail(500, e.getMessage());
    }

    @ExceptionHandler(value = RedisConnectionFailureException.class)
    public Result handleRedisConnectionFailureException(RedisConnectionFailureException e) {
        log.error("【错误异常】{}", e.getClass());
        log.error("【错误描述】{}", e.getMessage());
        return Result.fail(500, "Redis未启动");
    }

    @ExceptionHandler(value = Exception.class)
    public Result handleException(Exception e) {
        log.error("【错误异常】{}", e.getClass());
        log.error("【错误描述】{}", e.getMessage());
        e.printStackTrace();
        return Result.fail(StrUtil.isNotEmpty(e.getMessage()) ? e.getMessage() : "网络异常");
    }
}
